package com.aster.common.api.wechat.util;

import com.aster.common.api.wechat.domain.RepMess;
import com.aster.common.api.wechat.domain.WeChatFinalValue;
import com.aster.common.api.wechat.domain.WeChatOpenId;
import com.aster.common.api.wechat.domain.common.SNSUserInfo;
import com.aster.common.exception.ServiceException;
import com.aster.common.utils.HttpClientUtil;
import com.aster.common.utils.JSONUtils;
import com.aster.common.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;



/**
 * 微信操作工具类
 * 
 * @author tugou
 *
 */
public class WeChatUtil {

	 static Logger logger = LoggerFactory.getLogger(WeChatUtil.class);
	/**
	 * 页面授权，获取微信Openid
	 * 
	 * @param code
	 * @return
	 */
	public static WeChatOpenId getWeChatOpenid(String code) {
		String url = WeChatFinalValue.ACCESS_OPENID_URL;
		url = url.replaceAll("APPID",WXPayUtil.appId);
		url = url.replaceAll("SECRET",WXPayUtil.appsecret);
		url = url.replaceAll("CODE", code);
		logger.info("获取微信openid:" + url);
		String result = HttpClientUtil.doGet(url);
		logger.info("获取微信openid:" + result);
		Boolean isSuccess = checkRequestSucc(result);
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		WeChatOpenId content;
		try {
			if (isSuccess) {
				content = g.fromJson(result, WeChatOpenId.class);
			} else {
				RepMess mess = g.fromJson(result, RepMess.class);
				content = new WeChatOpenId();
				content.setMess(mess);
			}
			return content;
		}catch (Exception ex){
			ex.printStackTrace();
			return null;
		}
	}
	
	
	
	/**
	 * 通过网页授权获取用户信息
	 * 
	 * @param accessToken 网页授权接口调用凭证
	 * @param openId 用户标识
	 * @return SNSUserInfo
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) throws ServiceException {
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
		// 通过网页授权获取用户信息
		//JSONObject jsonObject = HttpsUtil.httpsRequest(requestUrl, "GET", null);
		String result = HttpClientUtil.doGet(requestUrl);
		if(StringUtils.isEmpty(result)){
			throw new ServiceException(55555,"返回微信数据为空");
		}
		if(!checkRequestSucc(result)){
			throw new ServiceException(55555,getRequestMsg(result));
		}
		SNSUserInfo snsUserInfo = (SNSUserInfo) JSONUtils.jsonToBean(result,SNSUserInfo.class);
		if(snsUserInfo == null){
			throw new ServiceException(55555,"获取用户信息异常");
		}
		return snsUserInfo;
	}

	/**
	 * 检查请求是否成功
	 * 
	 * @param content
	 * @return
	 */
	public static Boolean checkRequestSucc(String content) {
		Map<String, Object> map = JSONUtils.jsonToMap(content);
		if (!map.containsKey("errcode"))
			return true;
		Double errcode = (Double) map.get("errcode");
		if (errcode == 0)
			return true;
		return false;
	}

	/**
	 * 获取请求返回值
	 * 
	 * @param content
	 * @return
	 */
	public static Integer getRequestCode(String content) {
		Map<String, Object> map = JSONUtils.jsonToMap(content);
		if (map.containsKey("errcode"))
			return Integer.valueOf(Integer.valueOf(map.get("errcode").toString()));
		return -1;
	}

	/**
	 * 获取请求返回消息
	 * 
	 * @param content
	 * @return
	 */
	public static String getRequestMsg(String content) {
		Map<String, Object> map = JSONUtils.jsonToMap(content);
		if (map.containsKey("errcode"))
			return map.get("errmsg").toString();
		return null;
	}


}
